package com.apes.framework.plugin.esb.parser.element;


import com.apes.framework.plugin.esb.processor.ChainProcessor;
import com.apes.framework.plugin.esb.processor.idempotent.AntiHeavyProcessor;
import com.apes.framework.plugin.esb.processor.router.FilterProcessor;
import com.apes.framework.plugin.filereader.xml.ApesElement;
import org.springframework.stereotype.Component;


/**
 * 功能：idempotent元素解析器
 *
 * @author xul
 * @create 2019-11-21 15:39
 */
@Component
public class AntiHeavyElementParser extends AbstractProcessorParser {
    /**
     * 可解析的元素列表
     **/
    private final String[] elementNames = {"idempotent"};

    /**
     * 功能：可解析的元素列表
     */
    @Override
    public String[] getNames() {
        return elementNames;
    }

    @Override
    public ChainProcessor parse(ApesElement element) {
        String topic = element.getAttribute("topic");
        if (topic == null) {
            topic = getTopic(element);
            if (topic != null) {
                element.setAttribute("topic", topic);
            }
        }
        return super.parse(element);
    }

    private String getTopic(ApesElement element) {
        ApesElement parent = element.getParent();
        if (parent == null) return null;
        if (parent.getName().equals("chain")) {
            return parent.getAttribute("method");
        } else if(parent.getName().equals("consumer")){
            return parent.getAttribute("topic");
        }
        return getTopic(parent);
    }

    @Override
    <T extends Class> T getChainProcessorClass() {
        return (T) AntiHeavyProcessor.class;
    }
}
